package com.eventos;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;

import com.eventssmartphone.AplicacionEvents;
import com.eventssmartphone.JSONReaderListener;
import com.eventssmartphone.R;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class ActivityListadoSearchEventos extends Activity implements OnItemClickListener, OnClickListener, JSONReaderListener{
	ListView lista;
	ImageButton buscar;
	EditText paramBuscar;
	ProgressDialog myProgressDialog = null;
	List<EventoBean> listaEventos = new ArrayList<EventoBean>();
	String parametro = "";
	/**
	 * @see android.app.Activity#onCreate(Bundle)
	 */
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.ev_listaeventos);
		
		Bundle b = getIntent().getExtras();
		parametro = b.getString("parametro");
		
		lista = (ListView) findViewById(R.id.listaEventos);
		
		buscar = (ImageButton)findViewById(R.id.buscarEventos);        
        buscar.setOnClickListener(this);
        
        paramBuscar = (EditText)findViewById(R.id.searchBar);
		
		try{
                                
	        GestorEvento.getInstance().dameEventosSearch(parametro, this);
        
		} catch (Exception e){
			
        	Toast.makeText(this, "Error. Revise su conexión a Internet.", Toast.LENGTH_SHORT).show();

		}  
	}
	
	@Override
	public void onItemClick(AdapterView<?> adapter, View view, int position, long id) {
		EventoBean evento = (EventoBean)adapter.getItemAtPosition(position);
		Log.i("ejm", "Se seleccionó: " + evento.getTitEvento());
		//Toast.makeText(this, "Se seleccionó " + evento.getTitEvento(), Toast.LENGTH_LONG).show();
				
		Intent intent = new Intent(ActivityListadoSearchEventos.this, ActivityVerEvento.class);
		Bundle b = new Bundle();
		b.putInt("idEvento", evento.getIdEvento() ); 
		intent.putExtras(b); 
		((AplicacionEvents)this.getApplication()).setEventSource("Search");
		startActivity(intent);
	}
	
public void onClick(View v) {
		
		if (v.getId() == R.id.buscarEventos){
			if (filtrar(paramBuscar.getText().toString())){
				if (paramBuscar.getText().toString()!=null && paramBuscar.getText().toString().trim().length() != 0){
					Intent intent = new Intent(this, ActivityListadoSearchEventos.class);
					Bundle b = new Bundle();
					b.putString("parametro", paramBuscar.getText().toString()); 
					intent.putExtras(b); 
					startActivity(intent);
				}	
			} else Toast.makeText(this, "Caracter inválido.", Toast.LENGTH_SHORT).show();
		}
	}
	
	public boolean filtrar (String str){
		boolean valor =true;
		if (str.indexOf("/")!=-1) valor=false;
		if (str.indexOf("#")!=-1) valor=false;
		if (str.indexOf(";")!=-1) valor=false;
		if (str.indexOf(":")!=-1) valor=false;
		if (str.indexOf("?")!=-1) valor=false;
		if (str.indexOf("%")!=-1) valor=false;
		if (str.indexOf("\"")!=-1) valor=false;
		return valor;
	}
	
	@Override
	public void onConnected() {
		myProgressDialog = ProgressDialog.show(this, "Cargando...", "Por favor esperar...", true);
	}
 
	@Override
	public void onSent() {
		// TODO Auto-generated method stub
		myProgressDialog.setMessage("Procesando datos...");
	}

	@Override
	public void onFinished(JSONArray jArray) {
		try { 
			List<EventoBean> listaEventos = GestorEvento.getInstance().procesarDameEventosSearch(jArray, parametro);
			EventoAdapter adapter = new EventoAdapter(listaEventos, this);
			lista.setAdapter(adapter);
			lista.setOnItemClickListener(this);
			if (listaEventos.size()==0) {
	        	Toast.makeText(this, "No se encontraron resultados para la búsqueda.", Toast.LENGTH_SHORT).show();
	        }
		} catch (Exception e){
        	Toast.makeText(this, "Error. Revise su conexión a Internet.", Toast.LENGTH_SHORT).show();
		}  
		
		myProgressDialog.dismiss();
		
	}

	
}
